package com.efounder.frame.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.core.content.res.ResourcesCompat;
import androidx.viewpager.widget.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.manager.AppAccountResDownloader;
import com.efounder.frame.tabbar.CircleTextView;
import com.efounder.frame.title.EFPagerSlidingTabStripTitleView;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.frame.widget.EFArcMenuSuperScriptItem;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.mobilemanager.R;
import com.readystatesoftware.viewbadger.BadgeView;

import java.util.List;

/**
 * Created by XinQing on 2016/8/20.
 * EFAppAccountPagerSlidingTabFragment 辅助类
 */
public class EFAppAccountPagerSlidingTabFragmentHelper {
    /**
     * 右上角 角标
     **/
    private CircleTextView indicatorTextView;

    //private ImageView leftImageView;
    private UpdateResReceiver updateResReceiver;
    /**
     * 左上角 角标
     **/
    private BadgeView badgeView;
    private final String action = "com.efounder.updateres";

    private EFAppAccountPagerSlidingTabFragment.OnViewPagerMeasureCompleteDelegate
            onViewPagerMeasureCompleteDelegate;

    private EFAppAccountPagerSlidingTabFragment.EFAppAccountPagerSlidingTabFragmentListener
            fragmentListener;


    /**
     * 菜单管理类
     **/
    private EFAppAccountPagerSlidingTabFragmentMenuManager menuManager = new
            EFAppAccountPagerSlidingTabFragmentMenuManager();

    public EFAppAccountPagerSlidingTabFragment.OnViewPagerMeasureCompleteDelegate
    getOnViewPagerMeasureCompleteDelegate() {
        return onViewPagerMeasureCompleteDelegate;
    }

    public void setOnViewPagerMeasureCompleteDelegate(EFAppAccountPagerSlidingTabFragment
                                                              .OnViewPagerMeasureCompleteDelegate
                                                              onViewPagerMeasureCompleteDelegate) {
        this.onViewPagerMeasureCompleteDelegate = onViewPagerMeasureCompleteDelegate;
    }

    public EFAppAccountPagerSlidingTabFragment.EFAppAccountPagerSlidingTabFragmentListener
    getFragmentListener() {
        return fragmentListener;
    }

    public void setFragmentListener(EFAppAccountPagerSlidingTabFragment
                                            .EFAppAccountPagerSlidingTabFragmentListener
                                            fragmentListener) {
        this.fragmentListener = fragmentListener;
    }

    /***
     * 创建TitleView
     *
     * @param context
     * @param stubObject
     * @return
     */
    public EFPagerSlidingTabStripTitleView createTitleView(Context context, StubObject stubObject) {
        EFPagerSlidingTabStripTitleView titleView = new EFPagerSlidingTabStripTitleView(context);
        //根据配置，设置titleView 的 leftLayout
        configLeftLayout4TitleView(titleView, stubObject, context);
        //根据配置，设置titleView 的 RightLayout
        configRightLayout4TitleView(titleView, stubObject);
        return titleView;
    }

    /**
     * 根据配置文件，这只TitleView左侧View
     * @param titleView
     * @param stubObject
     * @param context
     */
    private void configLeftLayout4TitleView(EFPagerSlidingTabStripTitleView titleView, StubObject
            stubObject, Context context) {
        String leftIconName = stubObject.getString(EFXmlConstants.ATTR_LEFT_ICON, "");
        LinearLayout leftLayout = titleView.getLeftLayout();
        if ("".equals(leftIconName)) {
            leftLayout.setVisibility(View.INVISIBLE);
        } else {
            leftLayout.setVisibility(View.VISIBLE);
            ImageView leftImageView = titleView.getLeftImageView();
            setBadageView(context,leftImageView);
            leftImageView.setImageDrawable(Drawable.createFromPath(EFAppAccountUtils
                    .getAppAccountImagePath() + "/" + leftIconName));
            leftImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (fragmentListener != null) {
                        fragmentListener.onClickLeftViewListener(view);
                    }
                }
            });
        }

    }

    /**
     * 设置左上角角标（左上角应用号资源文件更新提示角标） yqs
     * @param context
     */
    public void setBadageView( Context context,View view ) {
        // 动态注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(action);
        updateResReceiver = new UpdateResReceiver();
        context.registerReceiver(updateResReceiver, filter);
        // if ("true") {
        badgeView = new BadgeView(context, view);
        badgeView.setText("1");
        badgeView.setTag("badge");
        badgeView.setBadgeMargin(5, 3);
        badgeView.setBadgeBackgroundColor(context.getResources().getColor(R.color.ef_green_dark));
        badgeView.setTextSize(12);
        if (AppAccountResDownloader.isNeedUpdate(EFAppAccountUtils.getAppAccountID())) {
            badgeView.show();
        } else {
            badgeView.hide();
        }

        // }
    }

    /**
     * 根据配置，设置titleView 的 RightLayout,并相应添加点击事件
     *
     * @param stubObject
     */
    private void configRightLayout4TitleView(EFPagerSlidingTabStripTitleView titleView,
                                             StubObject stubObject) {
        String menuType = stubObject.getString(EFXmlConstants.ATTR_MENU_TYPE, "");
        LinearLayout rightLayout = titleView.getRightLayout();
        if ("".equals(menuType)) {
            rightLayout.setVisibility(View.INVISIBLE);
        } else {
            rightLayout.setVisibility(View.VISIBLE);
            //重新布局rightLayout，添加图片和角标
            //1.删除原来布局
            rightLayout.removeAllViews();
            //2.添加 RelativeLayout
            int width = (int) rightLayout.getResources().getDimension(R.dimen
                    .ef_title_right_view_width);
            int height = (int) rightLayout.getResources().getDimension(R.dimen
                    .ef_title_right_view_height);
            RelativeLayout relativeLayout = new RelativeLayout(rightLayout.getContext());
            LinearLayout.LayoutParams relativeLayoutParams = new LinearLayout.LayoutParams(width,
                    height);
            relativeLayout.setLayoutParams(relativeLayoutParams);
            rightLayout.addView(relativeLayout);
            //3.添加ImageView
            ImageView menuImageView = new ImageView(rightLayout.getContext());
            menuImageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()) {
                        case MotionEvent.ACTION_UP:
//                            clearIndicator();
                            break;
                    }
                    return false;
                }
            });
            //添加背景选择器
            menuImageView.setBackgroundResource(R.drawable.ef_selector_transparent_background);
            RelativeLayout.LayoutParams menuImageViewParams = new RelativeLayout.LayoutParams
                    (width, height);
            menuImageView.setLayoutParams(menuImageViewParams);
            relativeLayout.addView(menuImageView);
            //TODO 根据menuType配置，设置不同图片，添加不同点击事件
            menuManager.configMenu(menuImageView, stubObject);
            //4.添加消息角标--指示器
            indicatorTextView = new CircleTextView(rightLayout.getContext());
            //XXX 暂时隐藏
//            indicatorTextView.setVisibility(View.GONE);
            indicatorTextView.setId(R.id.ids_title_right_indicator_view);
            RelativeLayout.LayoutParams indicatorParams = new RelativeLayout.LayoutParams
                    (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams
                            .WRAP_CONTENT);
            indicatorParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            indicatorParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            indicatorParams.rightMargin = (int) rightLayout.getResources().getDimension(R.dimen
                    .ef_title_right_indicator_view_margin);
            indicatorParams.topMargin = (int) rightLayout.getResources().getDimension(R.dimen
                    .ef_title_right_indicator_view_margin);
            indicatorTextView.setLayoutParams(indicatorParams);
            indicatorTextView.setGravity(Gravity.CENTER);
            indicatorTextView.setTextColor(ResourcesCompat.getColor(titleView.getResources(), R
                    .color.ef_white, null));
            indicatorTextView.setBackgroundColor(ResourcesCompat.getColor(titleView.getResources
                    (), R.color.ef_green_dark, null));
//            indicatorTextView.setTextSize(10);
            indicatorTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, rightLayout.getResources()
                    .getDimension(R.dimen.ef_title_right_indicator_view_text_size));
            int padding = (int) rightLayout.getResources().getDimension(R.dimen
                    .ef_title_right_indicator_view_text_padding);
            indicatorTextView.setPadding(padding, padding, padding, padding);
            //indicatorTextView 默认值为0
            clearIndicator();

            relativeLayout.addView(indicatorTextView);
        }
    }

    /**
     * 清除右上角角标（消息角标）
     */
    public void clearIndicator(){
        indicatorTextView.setText("0");
        indicatorAddNumber(0);
    }

    /**
     * 设置显示右上角角标（消息角标）
     * @param number
     */
    public void setIndicatorNumber(int number){
        if (null != indicatorTextView) {
            indicatorTextView.setText(number + "");
            if (number <= 0) {
                indicatorTextView.setVisibility(View.GONE);
            } else {
                indicatorTextView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 右上角角标（消息角标）加上某个数字
     * @param number
     */
    public void indicatorAddNumber(int number){
        String text = indicatorTextView.getText().toString();
        int originalNum = 0;
        try {
            originalNum = Integer.parseInt(text);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        number = originalNum + number;
        indicatorTextView.setText(number + "");
        if (number <= 0){
            indicatorTextView.setVisibility(View.GONE);
        }else {
            indicatorTextView.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 创建ViewPager
     *
     * @param context
     * @param childFragmentManager
     * @param dataList
     * @param tabPosition
     * @return
     */
    public ViewPager createViewPager(Context context, FragmentManager childFragmentManager,
                                     List<StubObject> dataList, final int tabPosition) {
        //1.创建viewPager
        final ViewPager viewPager = new ViewPager(context);
        LinearLayout.LayoutParams viewPagerParams = new LinearLayout.LayoutParams(ViewGroup
                .LayoutParams.MATCH_PARENT, 0);
        viewPagerParams.weight = 1;
        viewPager.setLayoutParams(viewPagerParams);
        //ViewPager必须设置id，否则会报错
        viewPager.setId(R.id.view_pager);
        //TODO 配置此项为100，会使viewPager中的左右100个fragment被全部创建
        viewPager.setOffscreenPageLimit(100);
//        viewPager.setOffscreenPageLimit(1);
        EFAppAccountPagerSlidingTabFragmentPagerAdapter adapter = new
                EFAppAccountPagerSlidingTabFragmentPagerAdapter(childFragmentManager, dataList);
        viewPager.setAdapter(adapter);

        viewPager.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        //隐藏Fragment
                        if (onViewPagerMeasureCompleteDelegate != null) {
                            onViewPagerMeasureCompleteDelegate.onViewPagerMeasureComplete
                                    (tabPosition);
                        }
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                            viewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            viewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }
                });


        return viewPager;
    }

    /***
     * EfPagerSlidingTabStrip 与 ViewPager关联
     *
     * @param efSlidingTabStripTitleView
     * @param viewPager
     */
    public void relateViewPager4SlidingTabTitleView(EFPagerSlidingTabStripTitleView
                                                            efSlidingTabStripTitleView, ViewPager
                                                            viewPager) {
        efSlidingTabStripTitleView.getEfPagerSlidingTabStrip().setViewPager(viewPager);
//        LinearLayout rightLayout = efSlidingTabStripTitleView.getRightLayout();
//        LinearLayout leftLayout = efSlidingTabStripTitleView.getLeftLayout();
        //隐藏LeftLayout
//        int tabCount = viewPager.getAdapter().getCount();
//        if (tabCount == 1){
//            //根据rightLayout显示状态，设置leftLayout状态
//            if (rightLayout.getVisibility() == View.VISIBLE){
//                leftLayout.setVisibility(View.INVISIBLE);
//            }else {
//                leftLayout.setVisibility(rightLayout.getVisibility());
//            }
//        }else {
//            leftLayout.setVisibility(View.GONE);
//        }
    }

    /**
     * 根据配置初始化ArcMenu（右下角悬浮菜单）
     * @param menu
     * @param menuStubList
     * @param isShowArcMenu 是否显示ArcMenu
     */
    public void initArcMenu(final ArcMenu menu, final List<StubObject> menuStubList, String isShowArcMenu) {
//        // 临时处理ArcMenu
//        ArcMenuList.arcMenuList.add(menu);
        if (menuStubList == null || menuStubList.size() == 0 || isShowArcMenu.equals("0")){
            menu.setVisibility(View.GONE);
            return;
        }
        for (int i = 0; i < menuStubList.size(); i++) {
            final EFArcMenuSuperScriptItem item = new EFArcMenuSuperScriptItem(menu.getContext(),
                    menuStubList.get(i));

            final int position = i;
            menu.addSuperscriptItem(item, new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (item.getSuperscriptNumber() <= 0){
                        Toast.makeText(v.getContext(),"请选择商品！",Toast.LENGTH_LONG).show();
                        return;
                    }
//                    // 更新角标
//                    EFArcMenuSuperScriptItem arcMenuItem = (EFArcMenuSuperScriptItem) v;
//                    arcMenuItem.superscriptAddNumber(1);

                    try {
//                        Bundle bundle = new Bundle();
                        Bundle bundle = EFFrameUtils.getCurrentActivity().getIntent().getExtras();
                        bundle.putInt("position", position);
                        StubObject menuStub = menuStubList.get(position);
                        bundle.putSerializable("stubObject", menuStub);
                        bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME, menuStub
                                .getCaption());
                        bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY,
                                View.INVISIBLE);
                        EFFrameUtils.pushFragment((Class<? extends Fragment>) Class.forName("com" +
                                ".efounder.chat.fragment.EFAppAccountFormFragment"), bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }
            });
            //TODO 初始化购物车中已有的数据
//            item.superscriptAddNumber(66);

        }
    }
//    public void initArcMenu(final ArcMenu menu, int[] itemDrawables) {
//        final int itemCount = itemDrawables.length;
//        for (int i = 0; i < itemCount; i++) {
//            ImageView item = new ImageView(menu.getContext());
//            item.setImageResource(itemDrawables[i]);
//
//            final int position = i;
//            menu.addItem(item, new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    Toast.makeText(menu.getContext(), "position:" + position, Toast
// .LENGTH_SHORT).show();
//                }
//            });
//        }
//    }

    //    public int[] getArcMenuItem(StubObject stubObject){
//        String name = stubObject.getCaption();
//        if ("采购".equals(name)){
//            return new int[]{R.drawable.icon_float_tg};
//        }else if ("运输".equals(name)){
//            return new int[]{R.drawable.composer_thought};
//        }else if ("供油".equals(name)){
//
//        }else if ("铁工".equals(name)){
//
//        }
//
//        return new int[]{};
//    }

    /**
     * 更新资源文件时监听广播，更改左上角角标
     */
    public class UpdateResReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String ac = intent.getAction();
            if (action.equals(ac) && "appaccountres".equals(intent.getStringExtra("type"))) {
                String num = intent.getStringExtra("num");
                if ("0".equals(num)) {
                    badgeView.hide();
                }else if ("1".equals(num)){
                    badgeView.show();
                }
            }

        }
    }

    public UpdateResReceiver getUpdateResReceiver() {
        return updateResReceiver;
    }


}
